#include<iostream.h>
#include<string.h>

#define MAXSYM 100
#define SEARCH 0
#define STORE 1

int locctr;

class symtabtype
{
 private:
  struct
   {
    char symbol[9];
    int loc;
    int occ;       // Occupied status
   } symtab[MAXSYM];

 public:
   symtabtype(); //Constructor
   int hash(char t[9]);
   int locof(char t[9]);
   int access(int mode, char t[9]);
};

symtabtype::symtabtype()
//Constructor
{
 for(int i=0;i<MAXSYM;i++)
  {
   strcpy(symtab[i].symbol,"        ");
   symtab[i].occ=0;
   symtab[i].loc=0;
  }
}

int hashval(char t[9])
/*Hashing function*/
{
 int value=0;
 for(int i=0;i<9;i++)
  value+=t[i];
 value=value%(MAXSYM+1);
 return(value);
}

int symtabtype::access(int mode, char t[9])
/*
This function is used to access the symbol table for the assembly.
If mode = search (0), the symbol is searched for in the table.
If mode = store  (1), the symbol is added to the table

The symbol table is organized as a hash table. The hashing function
simply sums the ordinal values of all of the characters in the symbol
Collisions are handled by linear probing.
*/
{
 int idx,found=0;

 idx=hashval(t);
 switch(mode)
 {
  case 0: if(symtab[idx].occ==0) return(0);
	  while(symtab[idx].occ== 1 && idx<MAXSYM && !found)
	   {if(strcmp(symtab[idx].symbol, t) == 0) found=1;
	    else idx++;}
	  return(found);

  case 1: if(symtab[idx].occ==0)
	   {
	     strcpy( symtab[idx].symbol, t);
	     symtab[idx].loc=locctr;
	     symtab[idx].occ=1;
	     return(1);
	   }
	  while(symtab[idx].occ== 1 && idx<MAXSYM && !found)
	   {
	    if(strcmp(symtab[idx].symbol, t) == 0) found=1;
	    else idx++;
	   }
	  if(found==1) return(0);
	  if(idx<MAXSYM)
	   {
	    strcpy( symtab[idx].symbol, t);
	    symtab[idx].loc=locctr;
	    symtab[idx].occ=1;
	    return(1);
	   }
	  else return(0);
 }
 return(0);
}

int symtabtype::locof(char t[9])
{
 int idx,found=0;
 idx=hashval(t);
 while(symtab[idx].occ== 1 && idx<MAXSYM && !found)
   {if(strcmp(symtab[idx].symbol, t) == 0) found=1;
     else idx++;}
   return(symtab[idx].loc);
}

